package com.mgm.test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.junit.Assert;

import com.mgm.utils.HttpConnectionUtil;

public class HttpUrlConnectionDemo {
	
	public static void main(String[] args) throws IOException {
		
		teset();
		
		Assert.assertFalse(false);
		
		URL url = new URL("http://api-pub.peg.cmcm.com/feed?key=i67nw0hdq8y6jkt9wof6pdvr0sl50ci7"); 

		URLConnection rulConnection = url.openConnection();// 此处的urlConnection对象实际上是根据URL的 
		          // 请求协议(此处是http)生成的URLConnection类 
		          // 的子类HttpURLConnection,故此处最好将其转化 
		          // 为HttpURLConnection类型的对象,以便用到 
		          // HttpURLConnection更多的API.如下: 

		HttpURLConnection connection = (HttpURLConnection) rulConnection; 
		
		//设置请求方式
        connection.setRequestMethod("GET");
        //连接
        connection.connect();
        //得到响应码
        int responseCode = connection.getResponseCode();
        if(responseCode == HttpURLConnection.HTTP_OK){
            //得到响应流
            InputStream inputStream = connection.getInputStream();
            //将响应流转换成字符串
            String result = stream2String(inputStream);//将流转换为字符串。
            System.out.println(result);
//            Log.d("kwwl","result============="+result);
        }

	}
	
	public static void teset() {
		String s = HttpConnectionUtil.doGet("https://appwalls.mobi/api/v1?pub_id=8732&api_key=AoqwL3z2w6jsX962lawwZlbkiSXOEvYs&incent=3&os=Android&country=ALL&c=10219");
		System.out.println(s);
	}
	
	public static String stream2String(InputStream is) throws IOException {
		if (is != null) {
			// ByteArrayOutputStream好处：边读，边缓冲数据
			// 可以捕获内存缓冲区的数据，转换成字节数组。
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int temp = -1;
			while ((temp = is.read(buffer)) != -1) {
				baos.write(buffer, 0, temp);
			}
			is.close();
			baos.close();
			return baos.toString();
		}
		return null;
	}
	
}
